package com.lge.clock.alarmclock;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.provider.MediaStore;
import android.net.Uri;
import android.database.Cursor;

import com.lge.clock.alarmclock.Alarms;
import com.lge.clock.alarmclock.AlarmMeta;
import com.lge.clock.util.Log;

public class PAReceiver extends BroadcastReceiver {
	private static final String TAG = "PAReceiver";
	
	public static final String ALARM_INSERT_ACTION	= "com.lge.clock.alarmclock.ALARM_INSERT_ACTION";
	public static final String ALARM_CHANGE_ACTION	= "com.lge.clock.alarmclock.ALARM_CHANGE_ACTION";

    @Override
	public void onReceive(Context context, Intent intent) {
    	ContentResolver resolver = context.getContentResolver(); 
    	
        if (ALARM_INSERT_ACTION.equals(intent.getAction())) {
            final String hour = intent.getStringExtra(AlarmMeta.COLUMNS.ALARM_HOUR);
            final String minutes = intent.getStringExtra(AlarmMeta.COLUMNS.ALARM_MINUTES);
            final int daysofweek = intent.getIntExtra(AlarmMeta.COLUMNS.ALARM_DAYSOFWEEK, 127);
            final String enabled = intent.getStringExtra(AlarmMeta.COLUMNS.ALARM_ENABLED);

            String[] PROJECTION1 = new String[] { "_id" };
            Cursor cc = null;
    		try {
				cc = resolver.query(Alarms.CONTENT_ALARMS_URI, PROJECTION1, null, null, null);
				if (cc != null) {
					if (cc.getCount() >= 15) {
						return;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if ( cc != null )
					cc.close();
			}
    		
            ContentValues values = new ContentValues();
            values.put(AlarmMeta.COLUMNS.ALARM_HOUR,		hour);
            values.put(AlarmMeta.COLUMNS.ALARM_MINUTES,		minutes);
            values.put(AlarmMeta.COLUMNS.ALARM_DAYSOFWEEK,	daysofweek);
            values.put(AlarmMeta.COLUMNS.ALARM_ENABLED,		enabled);
            values.put(AlarmMeta.COLUMNS.ALARM_SNOOZE,		"5");
            values.put(AlarmMeta.COLUMNS.ALARM_TONE,		defaultRingtone(context));
            values.put(AlarmMeta.COLUMNS.ALARM_VIB,			"On");
            values.put(AlarmMeta.COLUMNS.ALARM_PUZZLE,		"Off");        
            values.put(AlarmMeta.COLUMNS.ALARM_MEMO,		"");
            values.put(AlarmMeta.COLUMNS.ALARM_WIDGET_YN,	"N");
            resolver.insert(ALProvider.CONTENT_ALARMS_URI, values);

    		int maxID = 0;
    		
    		String[] PROJECTION2 = new String[] { "max(_id) ID" };
    		Cursor Cursor = null;
    		try {
    			Cursor = resolver.query(Alarms.CONTENT_ALARMS_URI, PROJECTION2, null, null, null);
				if (Cursor != null) {
					if (Cursor.moveToFirst()) {  
						maxID = Cursor.getInt(0);
						Log.d(TAG, "MAX ID=>" + maxID);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if ( Cursor != null )
					Cursor.close();
			}            
            ContentValues cvalues = null;
    		cvalues	= new ContentValues();

    		cvalues.put("hour", 		hour);
        	cvalues.put("minutes", 		minutes);     
    		cvalues.put("daysofweek",   daysofweek);
    		cvalues.put("enabled", 	    enabled); 
    		cvalues.put("stop",  	    "");
    		cvalues.put("aid",    		maxID);
    		cvalues.put("aindex", 		0);
    		cvalues.put("status", 		"A");
    		resolver.insert(ALProvider.CONTENT_CALCU_URI, cvalues);
    		if (maxID != 0) {
            	if ("1".equals(enabled) == true) {
            		Alarms.enableAlarm(context, maxID, true);
            	} else {
            		Alarms.enableAlarm(context, maxID, false);
            	}
    		}
    		else {
    			Alarms.setNextAlert(context);
    		}    			
        	return;
        }
        
        if (ALARM_CHANGE_ACTION.equals(intent.getAction())) {
        	final int mAlarmId = intent.getIntExtra(AlarmMeta.COLUMNS.ALARM_ID, 1);
        	final String enabled = intent.getStringExtra(AlarmMeta.COLUMNS.ALARM_ENABLED);
        	if ("1".equals(enabled) == true) {
        		Alarms.enableAlarm(context, mAlarmId, true);
        	} else {
        		Alarms.enableAlarm(context, mAlarmId, false);
        	}
            return;
        }
    }

	private static final String[] MEDIA_INTERNAL_COLUMNS = new String[] {
				android.provider.BaseColumns._ID,
				android.provider.MediaStore.MediaColumns.TITLE,
				"\"" + MediaStore.Audio.Media.INTERNAL_CONTENT_URI + "\"",
				android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY  
	};
	
	public String defaultRingtone(Context context) {
		String defaultTone = "";
	    Uri alert = RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM);
	    
		if (alert == null) {
			defaultTone = "Off";  
			return defaultTone ;
		}
		
		String temp = defaultRingtoneTitle(context);
        Log.d(TAG, "=>" + temp + "<=" );
		
	    ContentResolver resolver = context.getContentResolver();
	    Cursor cur = null;
		try {
			cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, MEDIA_INTERNAL_COLUMNS,
		               "is_alarm = 1",  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); 
			if (cur != null && cur.moveToFirst()) {
				do {
					Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
					int aa = (cur.getString(1)).indexOf( temp );
					if ( aa >=0 ) {
						Log.d(TAG, temp + " / Title=" +  cur.getString(1)  +   "<==  URI ==>" + uri1.toString());
						defaultTone	= uri1.toString();	
						break;
					}
				} while (cur.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cur != null)
				cur.close();
		}
	 	    
	 	if ("".equals(defaultTone.trim())) {
	 		defaultTone = "Off";
	 	}
	 	      
	 	Log.d(TAG, "====defaultTone======>" +  defaultTone );
	 	return defaultTone;
	}
      
    private String defaultRingtoneTitle(Context context) 
    {
    	Uri alert = RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM);
	    
    	if (alert != null) {
    		final Ringtone r = RingtoneManager.getRingtone(context, alert);
    		if (r != null) {
            	Log.d(TAG, "=default===> " + r.getTitle(context) );
            	return r.getTitle(context);  
            }
    	}
    	
    	return "";
	}    
}
